package com.example.night.data.InfluencerCoins;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Repository
public interface InfluencerCoinsRepository extends JpaRepository<InfluencerCoins, Long> {

    // 根据抖音 ID 查找达人记录
    Optional<InfluencerCoins> findByPromoteId(String promoteId);

    // 根据抖音名查找达人记录
    Optional<InfluencerCoins> findByPromoteName(String promoteName);

    List<InfluencerCoins> findByPromoteIdIn(List<String> promoteIds);
    // **更新金币数**
    @Transactional
    @Modifying
    @Query("UPDATE InfluencerCoins ic SET ic.coins = ic.coins + ?2 WHERE ic.promoteId = ?1")
    int updateCoins(String promoteId, int additionalCoins);

    // **提现操作，减少金币**
    @Transactional
    @Modifying
    @Query("UPDATE InfluencerCoins ic SET ic.coins = ic.coins - ?2, ic.withdrawnCoins = ic.withdrawnCoins + ?2 WHERE ic.promoteId = ?1 AND ic.coins >= ?2")
    int withdrawCoins(String promoteId, int coinsToWithdraw);

    // **根据 promoteId 更新部分信息（抖音名、电话、真实姓名）**
    @Transactional
    @Modifying
    @Query("UPDATE InfluencerCoins ic SET ic.promoteName = ?2, ic.phone = ?3, ic.name = ?4 WHERE ic.promoteId = ?1")
    int updateInfluencerInfo(String promoteId, String promoteName, String phone, String name);

    // **根据 promoteId 更新所有信息**
    @Transactional
    @Modifying
    @Query("UPDATE InfluencerCoins ic SET ic.promoteName = ?2, ic.phone = ?3, ic.name = ?4, ic.coins = ?5, ic.withdrawnCoins = ?6, ic.pendingWithdrawCoins = ?7 WHERE ic.promoteId = ?1")
    int updateAllInfluencerInfo(String promoteId, String promoteName, String phone, String name, int coins, int withdrawnCoins, int pendingWithdrawCoins);

    // **新增：根据 promoteId 修改 promoteId**
    @Transactional
    @Modifying
    @Query("UPDATE InfluencerCoins ic SET ic.promoteId = ?2 WHERE ic.promoteId = ?1")
    int updatePromoteId(String oldPromoteId, String newPromoteId);
}
